package com.scholarship.modules.login.service.impl;

import com.scholarship.common.utils.CommonUtil;
import com.scholarship.modules.login.entity.User;
import com.scholarship.modules.login.mapper.LUserMapper;
import com.scholarship.modules.login.service.LoginService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.Base64;

@Service("loginService")
public class LoginServiceImpl implements LoginService {

    @Autowired
    LUserMapper lUserMapper;

    @Override
    public String login(String userId, String password, Boolean rememberMe)
            throws UnknownAccountException,IncorrectCredentialsException {
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录数据
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(userId,password,rememberMe);
        //执行登录方法
        subject.login(usernamePasswordToken);
        //获取sessionID
        String sessionId = (String) subject.getSession().getId();

        return sessionId;
    }

    /**
     * 修改密码
     * @param email
     * @param password
     */
    @Override
    public void changePassword(String email, String password) {

        try {
            String baseStr = Base64.getEncoder().encodeToString(email.getBytes("utf-8"));
            User user = lUserMapper.getUserByEmail(baseStr);

            String saltPwd = CommonUtil.encryptPassword(password,user.getUserId());

            lUserMapper.updatePasswordByUserId(user.getUserId(),saltPwd);
        } catch (UnsupportedEncodingException e) {
            throw new UnsupportedOperationException("加密失败");
        }
    }
}
